今天可以說是非常忙的一天
,雖然大多時間都在畢業專題上,但我還是努力地寫出三題UVA,那就開始吧!
這題我寫這麼比較久,結果發現只是題目看不懂,哈哈...
#include<iostream>
#include <string>
using namespace std;
int main() {
 string a, b;
 char x;
 while (cin >> a >> b) {
  x = '\0';
  int size_a[97] = { 0 }; //size[97]為0代表沒有重複
  int size_b[97] = { 0 };
  for (int i = 0; i < a.length(); i++) {
   for (int j = 0; j < b.length(); j++) {
    if (a[i] == b[j]) {
     size_a[a[i] % 97] += 1; //a重複的次數
     break;
    }
   }
  }
  for (int i = 0; i < b.length(); i++) {
   for (int j = 0; j < a.length(); j++) {
    if (b[i] == a[j]) {
     size_b[b[i] % 97] += 1; //b重複的次數
     break;
    }
   }
  }
  for (int i = 0; i < 26; i++) { //找有重複且頻率最小的字母
   if (size_a[i] == 0) continue;
   else if (size_a[i] >= size_b[i]) {
    x = 'a' + i;
    cout << string(size_b[i], x); //a && b的集合
   }
   else {
    x = 'a' + i;
    cout << string(size_a[i], x);
   }
  }
  cout << endl;
 }
}
Vector是C++中的一個容器,可視為會自動擴展容量的array,寫 c++ 建議使用 vector 取代低階的 array
vec[i] - 存取索引值為 i 的元素值。
vec.push_back() - 新增元素至 vector 的尾端。
vec.pop_back() - 刪除 vector 最尾端的元素。
vec.clear() - 清空vector裡所有元素。
vec.size() - 取得 vector 的元素個數。
vec.begin() - 回傳一個 iterator,指向 vector 第一個元素。
vec.end() - 回傳一個 iterator,指向 vector 最尾端元素的下一個位置。
參考延伸閱讀:https://mropengate.blogspot.com/2015/07/cc-vector-stl.html
找到與所有親戚間總距離最小的位置,並求這個位置與其他所有親戚的距離和。
中位數與其他點的距離和會最小,所以先找到中位數,之後再取中位數與其他點的絕對值。
關於此題目的小提醒:
#include<bits/stdc++.h>
using namespace std;
int main(){
 int t;
 cin>>t;//輸入test case數
 while(t--){
 int r,ss;
 vector<int> s;
 
 cin>>r;//輸入有r個親戚
 s.clear();//記得要清空vector
 for(int i=0;i<r;i++){
 cin>>ss;//輸入每個親戚的位置      
 s.push_back(ss);//新增元素至 vector 的尾端
                 //前面要先用cin>>ss輸入才能新增元素喔!
    }
 sort(s.begin(),s.end());//排序
 int mid=s[r/2];//中位數
 int dis=0;//總距離
 for(int i=0;i<r;i++){
 dis+=abs(s[i]-mid);
 }
 cout<<dis<<endl;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
	
	string s,sn[100]={""};
	int num=0,maxlen=0;
	
	while(getline(cin,s)){
		sn[num]=s;
		if(sn[num].length()>maxlen) maxlen=sn[num].length();
		num++;
	}
	
	for(int k=0;k<maxlen;k++){
		for(int i=num-1;i>=0;i--){
			if(k>=sn[i].length()&&i!=0)cout<<" ";
			else if(k>=sn[i].length())continue;
			else cout<<sn[i][k];
		}
		cout<<endl;
	}
}